package com.demo.webapp.servlet;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.AccessDeniedException;

/**
 * 图片上传Servlet
 * 
 * @author ryuu.kk
 *
 */
public class DiskImageUploadServlet extends UploadServlet {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -8671562930413697860L;

	/**
	 * Spring容器上下文
	 */
	ApplicationContext applicationContext;
	
	public void init() {
		super.init();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Object writer(FileItem item, HttpServletRequest request, int index) throws Exception {
		
		//这里验证权限,有上传权限
		if (!isPermission()) {
			throw new AccessDeniedException("");
		}
		//~~ 取得上传文件参数 =====================================================================
        String fileName = item.getName();
        
        //String fieldName = item.getFieldName();
        //String contentType = item.getContentType();
       // boolean isInMemory = item.isInMemory();
        
        File file = null;
        //写文件
        String basePath = getFilePath();
        if (basePath.lastIndexOf("\\") != basePath.length()) {
        	basePath += "\\";
        }
        String folder = getFolder(request.getParameterMap(), index, "");
        String filePath = basePath + folder + "\\";
        
        if( fileName.lastIndexOf("\\") >= 0 ){
        	file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
        } else {
        	file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)) ;
        }
        if (!file.exists()) {
        	file.mkdirs();
        }
        item.write(file);
        
        return fileName;
	}
	
	/**
	 * 权限判断
	 * @return 是否有权限
	 */
	protected boolean isPermission() {
		//总是允许
		return true;
	}
	
	/**
	 * 返回目录地址
	 * @param params 参数map
	 * @param index 参数索引
	 * @param defaultId 默认目录 
	 * @return 目录
	 */
	protected String getFolder(Map<String, Object> params, int index, String defaultId) {
		String[] forderIds = (String[]) params.get("folderId");
		if (forderIds != null && forderIds.length > index) {
			return forderIds[index];
		}
		return defaultId;
	}
}